package com.yungu.swift.order.thread.inform;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

/**
 * 签名字符串生成类
 *
 * @author : cuixiuyin
 * @date : 2019/12/3
 */
@Slf4j
public class SignUtil {

    private static final String SIGN_KEY = "sign_key";
    private static final String SIGN_KEY_CONTENT = "dUGne3mTU146m8uL";

    /**
     * 将map格式参数按照key值按字符升序排列(key1value1key2value2)，拼接成字符串返回.
     * 该功能主要用于api对接中签名的加密前的参数拼接
     *
     * @param data
     * @return
     */
    public static String createSignStr(Map<String, String> data) {
        data.put(SIGN_KEY, SIGN_KEY_CONTENT);
        try {
            Iterator<String> iterator = data.keySet().iterator();
            Map<String, String> treeMap = new TreeMap<>();
            while (iterator.hasNext()) {
                String key = iterator.next();
                treeMap.put(key, JSON.toJSONString(data.get(key)));
            }
            Iterator<String> stringIterator = treeMap.keySet().iterator();
            StringBuilder stringBuilder = new StringBuilder();
            while (stringIterator.hasNext()) {
                String key = stringIterator.next();
                stringBuilder.append(key).append(treeMap.get(key));
            }
            System.out.println("sign字符串"+stringBuilder.toString().replace("\"", ""));
            log.debug("sign字符串：{}",stringBuilder.toString());
            return stringBuilder.toString().replace("\"", "");
        } catch (Exception e) {
            log.error("map转拼接字符串异常：{}", JSON.toJSONString(data), e);
        }
        return null;
    }
}
